package com.vf.cloud.server.render;

import com.vf.cloud.server.render.channel.Initializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.WriteBufferWaterMark;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RenderNMS implements Runnable {

	private EventLoopGroup boss;
	private EventLoopGroup work;
	private Channel channel;
	private int inetPort = 6666;

	public RenderNMS(int inetPort) {
		this.inetPort = inetPort;
	}

	@Override
	public void run() {
		try {
			ServerBootstrap bootstrap = new ServerBootstrap();
			boss = new NioEventLoopGroup();
			work = new NioEventLoopGroup();
			log.info(">>>正在启动RenderNMS: " + inetPort);
			bootstrap.group(boss, work);
			bootstrap.channel(NioServerSocketChannel.class);
			bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(512 * 1024, 1024 * 1024));
			bootstrap.childHandler(new Initializer());
			channel = bootstrap.bind(6666).sync().channel();
			channel.closeFuture().sync();
			log.info(">>>RenderNMS启动成功：" + channel);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			work.shutdownGracefully();
			boss.shutdownGracefully();
			log.info(">>>RenderNMS已关闭");
		}
	}

	public void close() {
		if (channel != null) {
			channel.close();
		}
		work.shutdownGracefully();
		boss.shutdownGracefully();
	}

}
